<template>
  <div class="container">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="quertInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="adddialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <el-table :data="userList" stripe style="width: 100%" border>
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态" prop="mg_state">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="switchChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editDilog(scope.row.id)"
           ></el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini"
            @click="removeUserById(scope.row.id)"></el-button>
            <el-tooltip effect="dark" content="编辑角色" placement="top">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRoleDiologvisble(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="quertInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="quertInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <!-- 弹框 -->
      <el-dialog title="添加用户" :visible.sync="adddialogVisible" width="50%" @close="addDioClose">
        <el-form :model="addForm" :rules="rules" ref="ruleForm" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="adddialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑用户弹框 -->
      <el-dialog title="编辑用户" :visible.sync="editDilogflag"
      width="50%" @close="editDioClose">
        <el-form :model="editForm" :rules="editRules" ref="editRef" label-width="70px">
          <el-form-item label="用户名" >
            <el-input :disabled="true" v-model="editForm.username"
             ></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDilogflag = false">取 消</el-button>
          <el-button type="primary" @click="editUserinfo">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑角色弹框 -->
        <el-dialog title="编辑角色" :visible.sync="setRoledialogVisible" width="50%"
        @close="setRolesClose">
          <p>当前的用户：{{userInfo.username}}</p>
          <p>当前的角色：{{userInfo.role_name}}</p>
            <el-select v-model="seleId" placeholder="请选择">
              <el-option
                v-for="item in rolesList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
              </el-option>
            </el-select>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRoledialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setRolesInfo">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    // 验证邮箱
    var checkEmail = (rule, value, cb) => {
      const regEmail = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/
      if (regEmail.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法邮箱'))
    }
    var checkPhone = (rule, value, cb) => {
      const regPhone = /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
      if (regPhone.test(value)) {
        return cb()
      }
      cb(new Error('请输入合法手机号'))
    }
    return {
      quertInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: '' || 2,
      adddialogVisible: false,
      addForm: {
        username: '',
        email: '',
        mobile: '',
        password: ''
      },
      editDilogflag: false,
      editForm: {
        username: '',
        email: '',
        mobile: ''
      },
      // 控制编辑角色弹框
      setRoledialogVisible: false,
      // 角色信息
      userInfo: {},
      // 角色列表
      rolesList: [],
      // 选中的ID
      seleId: '',
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ],
        password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
      },
      // 编辑用户的校验规则
      editRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkPhone, trigger: 'blur' }
        ]
      }
    }
  },
  mounted () {
    this.getUserList()
  },
  methods: {
    async getUserList () {
      const { data: res } = await this.$axios.get('users', {
        params: this.quertInfo
      })

      if (res.meta.status !== 200) {
        this.$message.error('获取数据失败')
      } else {
        this.userList = res.data.users
        this.total = res.data.total
      }
    },
    handleSizeChange (newSize) {
      this.quertInfo.pagesize = newSize
      this.getUserList()
    },
    handleCurrentChange (newNum) {
      this.quertInfo.pagenum = newNum
      this.getUserList()
    },
    async switchChange (statu) {
      console.log(statu)
      const { data: res } = await this.$axios.put(
        `users/${statu.id}/state/${statu.mg_state}`
      )
      if (res.meta.status !== 200) {
        status.mg_state = !status.mg_state
        return this.$message.error('修改失败')
      } else {
        this.$message.success('修改状态成功')
      }
    },
    addDioClose () {
      this.$refs.ruleForm.resetFields()
    },
    addUser () {
      this.$refs.ruleForm.validate(async valid => {
        if (!valid) return this.$message.error('数据校验失败')
        const { data: res } = await this.$axios.post('users', this.addForm)
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败')
        } else {
          this.$message.success('添加用户成功')
          this.adddialogVisible = false
          this.getUserList()
        }
      })
    },
    async  editDilog (id) {
      this.editDilogflag = true
      const { data: res } = await this.$axios.get(`users/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('获取信息时报')
      } else {
        this.editForm = res.data
      }
    },
    editDioClose () {
      this.$refs.editRef.resetFields()
    },
    editUserinfo () {
      this.$refs.editRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('信息输入不合法')
        }
        const { data: res } = await this.$axios.put(`users/${this.editForm.id}`, {
          email: this.editForm.email,
          mobile: this.editForm.mobile
        })
        if (res.meta.status !== 200) {
          return this.$message.error('更新用户信息失败')
        }
        this.getUserList()
        this.$message.success('更新用户信息成功')
        this.editDilogflag = false
      })
    },
    async  removeUserById (id) {
      const res = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (res !== 'confirm') {
        this.$message('取消了删除')
      } else {
        const res1 = await this.$axios.delete(`users/${id}`)

        if (res1.data.meta.status !== 200) {
          return this.$message.err('删除失败')
        }
        this.$message.success('删除成功')
        this.getUserList()
      }
    },
    // 控制编辑角色的弹框
    async  setRoleDiologvisble (user) {
      this.userInfo = user
      // 获取角色列表
      const { data: res } = await this.$axios.get('roles')
      this.rolesList = res.data
      this.setRoledialogVisible = true
    },
    // 点击确定按钮，设置角色信息
    async  setRolesInfo () {
      if (!this.seleId) {
        return this.$message.error('角色信息不能为空')
      }
      const { data: res } = await this.$axios.put(`users/${this.userInfo.id}/role`, { rid: this.seleId })
      console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error('设置角色失败')
      }
      this.$message.success('角色设置成功')
      this.getUserList()
      this.setRoledialogVisible = false
    },
    // 弹框关闭前
    setRolesClose () {
      this.seleId = ''
      this.userInfo = ''
    }
  }
}
</script>

<style>
</style>
